<template>
  <div class="userinfo">
    <div class="top">
      <van-nav-bar title="个人信息" left-arrow @click-left="$router.back()" />
    </div>
    <div class="main">
      
        <div class="img">
          <i>头像</i>
          <input
            id="file"
            accept="image/*"
            @change="uploadImage"
            type="file"
            style="display: none"
          />

          <div class="img-r">
            <label for="file" class="iconfont" style="margin-right: 20px">
              <van-image
                round
                width="50"
                height="50"
              :src="userInfo.avatar || require('@/assets/photo.png')"
              />
            </label>
            <span> <van-icon name="arrow" /></span>
          </div>
        </div>
        <!-- <van-cell-group>
        <van-cell class="avatar" type="file" title="头像" size="large" is-link>
          <van-image @click="uploadImage" round class="img" width="50" height="50" :src="Src"
        /></van-cell>-->
        <van-field
          v-model="userInfo.nickname"
          label="昵称"
          is-link
          input-align="right"
        />

        <!-- 性别选择 -->
        <van-field
          readonly
          clickable
          name="sex"
          label="性别"
          :value="userInfo.sex"
          input-align="right"
          is-link
          @click="sexShow = true"
        />
        <van-popup v-model="sexShow" position="bottom">
          <van-picker
            show-toolbar
            :columns="['男', '女']"
            @confirm="sexConfirm"
            @cancel="sexShow = false"
          />
        </van-popup>

        <!-- 生日 -->

        <van-field
          v-model="userInfo.birthday"
          label="生日"
          name="birthday"
          is-link
          input-align="right"
        />
     
      <van-button class="button" block type="primary" size="normal"
      @click="submit"
        >确定</van-button
      >
    </div>
  </div>
</template>

<script>
import { Cell, CellGroup, Picker, Popup, DatetimePicker } from "vant";

export default {
  data() {
    return {
   
     
      sexShow: false,

      userInfo:[]
    };
  },
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [DatetimePicker.name]: DatetimePicker,
  },
  created() {
    this.getuserInfo()
  },
  methods: {
    // 性别
    sexConfirm(value) {
      this.userInfo.sex = value;
      this.sexShow = false;
    },
    getuserInfo() {
      let token = localStorage.getItem("tt-token");
      if (!token) {
        this.$toast("缺少参数");
        setTimeout((v) => {
          this.$router.back();
        }, 800);
        return;
      }
      this.$http.post("/user/getuserInfo", {token}).then((res)=>{
        if (res.code==0) {
         this.userInfo=res.userInfo
        }
      })
    },
    getUploadToken() {
      return this.$http.get(
        "https://d33a5037-6c63-4e92-8bb1-30018ab701ea.bspapp.com/http/upload/token"
      );
    },

    async uploadImage(e) {
      console.log(e.target.files[0]);
      //   选择完就上传
      let file = e.target.files[0];
      console.log(file);

      try {
        //  先去申请一个token
        let { token } = await this.getUploadToken();
        console.log(token);

        // 申请以后把file 和token还有文件名一起发给服务器
        let exname = file.name.slice(file.name.lastIndexOf(".") + 1);
        let Key = `${new Date().getTime()}_${Math.random()
          .toString(36)
          .slice(2)}.${exname}`;
        let formData = new FormData();
        formData.append("token", token);
        formData.append("file", file);
        formData.append("Key", Key);
        this.$http
          .post("https://upload-z1.qiniup.com", formData)
          .then((res) => {
            console.log(res);
            this.userInfo.avatar = `http://toutiao.longxiaokj.com/` + res.key;

            //   强制更新
            this.$forceUpdate();
          });
        console.log(Key);
      } catch (error) {
        console.log(error);
        this.$toast(error);
      }
    },
     submit() {
      let { avatar, nickname, sex, birthday} = this.userInfo;
      let uid = localStorage.getItem("tt-uid");

      // 校验
      this.$http
        .post("/user/editUserInfo", {
          avatar,
          nickname,
          sex,
          birthday,
          uid
        })
        .then((res) => {
          console.log(res);
          if (res.code==0) {
            this.$toast('修改成功')
            let{userInfo}=res
            // 让userInfo也更新一下
            this.$root.userInfo=userInfo;
            localStorage.setItem('tt-userInfo',JSON.stringify(userInfo))
            setTimeout(v => {
              this.$router.back()
            }, 800);
          }else{
            this.$toast('修改失败')
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.img {
  background-color: #fff;
  font-size: 14px;
  padding: 10px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    font-style: normal;
  }

  .img-r {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.userinfo {
  height: 100vh;
  background-color: rgb(245, 247, 249);
  .avatar {
    align-items: center;
  }
  .button {
    margin: 0 auto;
    width: 70%;
    margin-top: 20px;
  }
}
</style>